package org.jeecg.modules.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
public class Test {

    public static void main(String[] args) {
        //初始化60个数据
        List<String> list = new ArrayList<>();
        int size = 60;
        for (int i = 0; i < size; i++) {
            list.add("task-"+i);
        }
        //处理完成后的结果集
        List<String> results = new ArrayList<>();
//        long millis = System.currentTimeMillis();
//        System.out.println("=========不使用多线程处理数据============");
//        System.out.println("===============开始解析=================");
//        results.addAll(execute(list));
//        System.out.println("解析完成,解析数据量:"+results.size()+",耗时:"+(System.currentTimeMillis() - millis) / 1000 + "秒");
//        results.clear();
        System.out.println("===============分割线===================");
        System.out.println("===========使用多线程处理数据============");
        System.out.println("===============开始解析=================");
        long millis1 = System.currentTimeMillis();
        try {
            ThreadPoolUtil<List<String>> threadPoolUtil = ThreadPoolUtil.getInstance();
            List<Future<List<String>>> futureList = new ArrayList<>();
            //这里根据线程池的核心数去进行分段处理，最好不要一开始就达到最大线程数，只需要一半即可
            int numThreads = Runtime.getRuntime().availableProcessors() / 2;
            for (int i = 0; i < list.size(); i += list.size() / numThreads) {
                int start = i;
                int end = Math.min(i + list.size() / numThreads, list.size());
                List<String> subList = list.subList(start, end);
                Callable<List<String>> task = () -> {
                    return execute(subList);
                };
                Future<List<String>> future = threadPoolUtil.submitTask(task);
                futureList.add(future);
            }
            for (Future<List<String>> future : futureList) {
                results.addAll(future.get());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("解析完成,解析数据量:"+results.size()+",耗时:"+(System.currentTimeMillis() - millis1) / 1000 + "秒");

    }

    private static List<String> execute(List<String> subList){
        List<String> result = new ArrayList<>();
        for (String s : subList) {
            try {
                //模拟耗时每次1s
                Thread.sleep(1000);
                result.add(s + Thread.currentThread().getName());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }

}

